package com.cjzuji.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cjzuji.rental.Bean.XWuRequest;
import com.cjzuji.rental.Config.XWuConfig;
import com.cjzuji.rental.dao.*;
import com.cjzuji.rental.mapper.OrderBillMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.pojo.OrderBill;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.service.XWuService;
import com.cjzuji.rental.service.YouPinService;
import com.cjzuji.rental.util.Tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.math3.analysis.solvers.UnivariateSolverUtils;
import org.apache.commons.math3.geometry.spherical.oned.S1Point;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class XWuServiceImpl implements XWuService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    XWuOrderDao xWuOrderDao;
    @Autowired
    XWuUserDao xWuUserDao;
    @Autowired
    XWuContractDao xWuContractDao;
    @Autowired
    XWuBillDao xWuBillDao;
    @Autowired
    XWuConfig xWuConfig;
    @Autowired
    OrderBillMapper orderBillMapper;
    private static final Logger logger = LoggerFactory.getLogger(XWuServiceImpl.class);
    @Override
    //http://127.0.0.1:9099/order/youping/getListInfo
    public List<Map<String, Object>> getOrdersList(String token,String cookie, String randomCode) {
        String url = xWuConfig.getGetListUrl();
        XWuRequest xWuRequest = new XWuRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        xWuRequest.setPageNumber(1);
        xWuRequest.setPageSize(10);
        int pageNum = 1;  // 从第一页开始
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                xWuRequest.setPageNumber(pageNum);
                String json = objectMapper.writeValueAsString(xWuRequest);
                String resStr = Tool.request(url,cookie,token,json, "");
                logger.info(resStr);
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                // 获取 data → list
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                //logger.info("dataMap~~ {}",dataMap);
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("records");
                logger.info("list~~~ {}",list);
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                        String orderId = item.get("order_id").toString();
                        //详情
                        Map<String,Object> detail = getDetailes(token, orderId);
                        //获取电话
                        Map<String,Object> orderInfo = (Map<String, Object>) detail.get("orderAddressDto");
                        String phoneKey = orderInfo.get("telephoneKey").toString() ;
                        String phone = getPhone(token, cookie,randomCode, orderId, phoneKey);
                        //获取合同
                        List<String> contract = getContract(token, cookie, orderId);
                        //获取分配人
                        List<Map<String, Object>> assignerList = getAllotUser(token, cookie, orderId);
                        String assigner = "";
                        if (assignerList != null && assignerList.size() > 0){
                            assigner = assignerList.get(0).get("userName").toString();
                            System.out.println("分配人："+assigner);
                        }

                        logger.info("contract {}",contract);
                        // 判断 当前的订单号是否在数据库中存在
                        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("order_id",orderId);
                        List<Orders> existingOrder = orderMapper.selectList(queryWrapper);
                        logger.info("existingOrder {}",existingOrder);
                        if (existingOrder.size() > 0 ) {
                            logger.info("订单已存在，对订单进行更新");
                            //更新订单状态，快递单号,更新分配人
                            Orders existing = existingOrder.get(0);
                            updateExistingOrder(existing,item,detail,orderId,assigner,contract);
                        }
                        else{
                            // 保存数据
                            System.out.println("进去开始保存order~~~~~~~~~~~~~~"+orderId);
                            Long orderID = xWuOrderDao.save(item, detail, phone,assigner);
                            System.out.println("保存user~~~~~~~~~~~~~"+orderID);
                            xWuUserDao.save(orderID,item,detail, phone);
                            //保存合同
                            System.out.println("订单状态~~~~~~~"+item.get("order_status").toString());
                            if ("106".equals(item.get("order_status").toString())) {
                                System.out.println("进去开始保存contract~~~~~~~~~~~~~~"+orderID);
                                xWuContractDao.save(contract,orderID);
                                System.out.println("保存bill~~~~~~~~~~~~");
                                xWuBillDao.save(detail,orderID);
                            }
                        }
                    }
                }else {
                    break;
                }
                pageNum ++;
                logger.info("打印当前页码 {}",pageNum);

            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
        }
        return listData;
    }
    //更新订单数据
    private void updateExistingOrder(Orders existingOrder, Map<String, Object> item,Map<String,Object> detail,String orderId,String assigner,List<String> contract){
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", existingOrder.getId());
        //更新订单状态,更新分配人
        int newStatus = getOrderStatus(item.get("order_status").toString());
        updateWrapper.eq("order_id", orderId)
                .set("status", newStatus)
                .set("assigner", assigner);
        logger.info("更新订单状态 {}",newStatus);
        orderMapper.update(updateWrapper);
        //如果订单状态变为了3 ，还要添加合同表和账单表
        //更新快递单号
        if (newStatus == 3){
            //更新快递单号和账单表
            Map<String, Object> deliveryList = (Map<String, Object>) detail.get("receiptExpressInfo");
            updateWrapper.eq("order_id", orderId)
                    .set("delivery_no", deliveryList.get("expressNo"));
            logger.info("更新快递单号 {}",deliveryList.get("expressNo"));
            orderMapper.update(updateWrapper);
            //查询账单表是否存在该order_id,不存在添加账单
            QueryWrapper<OrderBill> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orders_id",orderId);
            List<OrderBill> existingBill = orderBillMapper.selectList(queryWrapper);
            logger.info("查询到的已存在账单数量: {}",existingBill.size());
            // 订单已存在
            if (!existingBill.isEmpty() ) {
//                Long orderID = existingBill.get(0).getOrderId();
//                // 订单已存在，对比两方的“还款状态”数据，如果相同不变，不同对数据库账单表进行更新
                logger.info("订单已存在~~,对比更新数据",orderId);
//                compareUpdate(bill,existingBill,orderID);
            }
            else {
                System.out.println("进去开始保存contract~~~~~~~~~~~~~~"+orderId);
                xWuContractDao.save(contract,existingOrder.getId());
                System.out.println("保存bill~~~~~~~~~~~~");
                xWuBillDao.save(detail,existingOrder.getId());
            }
        }
    }

    //更新账单表，对比更新代码
    

    // 订单状态映射方法
    public int getOrderStatus(String  status) {
        switch (status) {
            case "104":
                return 1;
            case "105":
                return 1;
            case "130":
                return 0;
            case "106":
                return 3;
            default:
                return 7;
        }
    }
    //获取电话
    public String getPhone(String token,String cookie ,String randomCode,String orderId,String phoneKey) throws JsonProcessingException {
        try {
            //url编码phoneKey
            String codePhoneKey = java.net.URLEncoder.encode(phoneKey,"utf-8");
            //logger.info("打印编码后的phoneKey {}",codePhoneKey);
            String url = xWuConfig.getGetphoneUrl()+ codePhoneKey + randomCode;
            //System.out.println("url~~~~~"+url);
            String phoneStr = Tool.getRequest(url,cookie,token);
            ObjectMapper phoneMapper = new ObjectMapper();
            Map<String,Object> phonedate = phoneMapper.readValue(phoneStr,Map.class);
            //logger.info("phonedate~~~~~{}",phonedate);
            String phone = phonedate.get("data").toString();
            System.out.println("phone~~~~~"+phone);
            return phone ;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //获取详情
    public Map<String,Object> getDetailes(String token, String orderId) throws JsonProcessingException {
        System.out.println("orderId~~~~~"+orderId);
        XWuRequest xWuRequest = new XWuRequest();
        xWuRequest.setOrderId(orderId);
        ObjectMapper objectMapper = new ObjectMapper();
        String JSON=objectMapper.writeValueAsString(xWuRequest);
        String detailUrl =xWuConfig.getGetDetailUrl();
        //post
        String detailStr =  Tool.request(detailUrl,"",token,JSON,"");
        ObjectMapper DetailMapper = new ObjectMapper();
        Map<String,Object> detail = DetailMapper.readValue(detailStr,Map.class);
        Map<String,Object> detailMap = (Map<String, Object>) detail.get("data");
        System.out.println("订单详情~~~~~"+detailMap);
        return detailMap;
    }
    //获取合同
    public List<String> getContract(String token, String cookie , String orderId) throws JsonProcessingException {
        String contractUrl =xWuConfig.getGetContractUrl() + orderId;
        String contractStr =  Tool.getRequest(contractUrl,cookie,token);
        ObjectMapper rescontractMapper = new ObjectMapper();
        Map<String,Object> resCon=rescontractMapper.readValue(contractStr,Map.class);
        List<String> contractList = (List<String>) resCon.get("data");
        return  contractList;
    }
    //获取分配人
    public List<Map<String, Object>> getAllotUser(String token, String cookie , String orderId) throws JsonProcessingException {
        String assignerUrl ="https://admin.jizhouyoupin.com/hzsx/business/order/queryOrderRemark";
        XWuRequest xWuRequest = new XWuRequest();
        xWuRequest.setOrderId(orderId);
        xWuRequest.setPageNumber(1);
        xWuRequest.setPageSize(3);
        xWuRequest.setSource("02");
        ObjectMapper objectMapper = new ObjectMapper();
        String JSON=objectMapper.writeValueAsString(xWuRequest);
        // post
        String assignerStr =  Tool.request(assignerUrl,cookie,token,JSON,"");
        ObjectMapper assignerMapper = new ObjectMapper();
        Map<String,Object> assigner = assignerMapper.readValue(assignerStr,Map.class);
        System.out.println("分配人~~~~~"+assigner);
        Map<String,Object> assignerMap = (Map<String, Object>) assigner.get("data");
        System.out.println("分配人~~~~~"+assignerMap);
        List<Map<String,Object>> assignerList = (List<Map<String, Object>>) assignerMap.get("records");
        System.out.println("分配人~~~~~"+assignerList);
        return assignerList;
    }
}